package com.suning.sawp.web.controller;

import java.security.Principal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.bi.OmsOrderItemPos;
import com.suning.sawp.dto.bi.StoreManDevMemberData;
import com.suning.sawp.dto.bi.StoreManRealIncomeList;
import com.suning.sawp.dto.clerk.IncomeOrderRtn;
import com.suning.sawp.dto.clerk.SourceRtn;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.promotion.PromotionDetail;
import com.suning.sawp.intf.bi.BiDataDaoService;
import com.suning.sawp.intf.report.ReportService;
import com.suning.sawp.po.bi.StoreManThisMonIncomeDetail;
import com.suning.sawp.po.bi.StoreManTotalIncome;
import com.suning.sawp.service.util.BaseContants;
import com.suning.sawp.service.util.ConfigUtil;
import com.suning.sawp.service.util.DJStringUtils;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.web.exception.MobileException;
import com.suning.sawp.web.exception.MyGsonView;
import com.suning.vgs.follow.remote.intf.StoreManRemoteService;

/**
 * 查询统计信息 ，销售提成明细，会员发展明细
 * 
 * @author 14062606
 * @see [相关类/方法]
 * @since
 */
@Controller
@RequestMapping("/report")
public class ReportController extends DjBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    @Resource
    ReportService reportService;

    @Resource
    BiDataDaoService biDataDaoService;

    @Resource
    StoreManRemoteService storeManRemoteService;

    /**
     * 
     * 功能描述:查询会员发展明细 <br>
     * 〈功能详细描述〉
     *
     * @param currIndex 起始
     * @param pageSize 分页大小
     * @param promoteDate 发展时间（0昨日发展 1本月发展 2上月发展（默认本月））
     * @param promotionSrc 发展渠道 （传空表示所有渠道）
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryPromotionList.do")
    public MyGsonView queryPromotionList(@RequestParam(value = "currIndex", required = false) int currIndex,
            @RequestParam(value = "pageSize", required = false) int pageSize,
            @RequestParam(value = "promoteDate", required = false) String promoteDate,
            @RequestParam(value = "promotionSrc", required = false) String promotionSrc, Principal principal) {

        String staffId = principal.getName();
        // 设置默认的页面大小和起始位置20,0
        if (pageSize < 1) {
            pageSize = 20;
        }

        PromotionDetail detail = new PromotionDetail();
        try {
            detail = reportService.queryPromotionList(currIndex, pageSize, promoteDate, promotionSrc, staffId);
        } catch (Exception e) {
            Object[] errArgs = { currIndex, pageSize, promoteDate, promotionSrc, staffId, e };
            LOGGER.error("查询会员发展明细发生异常，currIndex:{}, pageSize:{}, promoteDate:{}, "
                    + "promotionSrc:{}, staffId:{}, error:{}", errArgs);
        }

        MyGsonView view = createGsonView();
        view.addStaticAttribute(BaseContants.DATA, detail);

        return view;
    }

    /**
     * 查询会员汇总数据 昨日发展,本月发展,累计发展 昨天提成,本月提成,累计提成 默认-
     * 
     * @param principal
     * @return
     */
    @RequestMapping("/queryOverview.do")
    public MyGsonView queryClerkCollectData(Principal principal) throws Exception {
        // 返回结果
        Map<String, Object> data = getDefaultOverViewData();

        // 调用会员发展统计查询接口
        try {
            StoreManDevMemberData memberData = reportService.queryPosDevMemberData(principal.getName());
            data.put("yesterdayPromotion", memberData.getYesterdayPromotion());
            data.put("promotionTotal", memberData.getPromotionTotal());
            data.put("curMonthPromotion", memberData.getCurMonthPromotion());
            // 增加统计时间
            data.put("promotionStatisDate", changeDateStr(""));
        } catch (Exception e) {
            LOGGER.error("查询会员汇总数据.调用会员发展统计接口发生异常，staffId:{}, error:{}", principal.getName(), e);

            String errorCode = ErrorCodeConstants.ERR_0002;
            throw new MobileException(errorCode, ErrorCodeConstants.ERR_MAP.get(errorCode));
        }

        StoreManTotalIncome income = null;
        try {
            // 查询销售提成详情
            income = biDataDaoService.queryTotalIncomeBySatffIdAndDate(principal.getName(),
                    DateUtils.getNextDayStr(-1, DateUtils.YYYYMMDD_PATTERN), "", true);
        } catch (Exception e) {
            LOGGER.error("查询会员汇总数据.调用销售提成统计查询接口发生异常，staffId:{}, error:{}", principal.getName(), e);
            String errorCode = ErrorCodeConstants.ERR_0002;
            throw new MobileException(errorCode, ErrorCodeConstants.ERR_MAP.get(errorCode));
        }

        // 存在记录
        if (null != income) {
            Double actIncome = income.getActIncome();
            Double monActIncome = income.getMonActIncome();
            Double totalActIncome = income.getTotalActIncome();
            // 不为空
            if (null != actIncome) {
                data.put("yesterdayCommission", DJStringUtils.stringFormat(actIncome.toString()));
            }
            // 不为空
            if (null != monActIncome) {
                data.put("curMonthCommission", DJStringUtils.stringFormat(monActIncome.toString()));
            }
            // 不为空
            if (null != totalActIncome) {
                data.put("commissionAmount", DJStringUtils.stringFormat(totalActIncome.toString()));
            }
            // 增加统计时间
            data.put("amountStatisDate", changeDateStr(income.getStatisDate()));
        } else {
            // 增加统计时间
            data.put("amountStatisDate", "-");
        }
        // 提成暂时关闭，不再展示提成相关信息
        data.put("amountStatisDate", "-");
        MyGsonView view = createGsonView();
        view.addStaticAttribute(BaseContants.DATA, data);
        return view;
    }

    private Map<String, Object> getDefaultOverViewData() {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("commissionAmount", "0.00");
        data.put("curMonthCommission", "0.00");
        data.put("yesterdayCommission", "0.00");

        data.put("yesterdayPromotion", 0);
        data.put("curMonthPromotion", 0);
        data.put("promotionTotal", 0);

        return data;
    }

    /**
     * 查询销售提成详情
     * 
     * @param principal
     * @param pageSize
     * @param startIndex
     * @param timeType
     * @param sourceId
     * @return
     */
    @RequestMapping("/queryCommssionList.do")
    public MyGsonView queryIncomeDetailPage(Principal principal,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "currIndex", required = false) Integer currIndex,
            @RequestParam(value = "commssionDate", required = false) String commssionDate,
            @RequestParam(value = "commssionSrc", required = false) String commssionSrc) throws Exception {
        LOGGER.debug("enter queryCommssionList");

        // 返回结果
        Map<String, Object> data = getDefaultCommssionListData();

        LOGGER.debug("pageSize, " + pageSize);
        LOGGER.debug("startIndex, " + currIndex);

        // 设置默认的页面大小和起始位置20,0
        if (null == pageSize || pageSize < 1) {
            pageSize = 20;
        }
        if (null == currIndex || currIndex < 0) {
            currIndex = 0;
        }

        // 如果是首页,拼接文案, 查询来源列表
        if (currIndex == 0) {
            MessageFormat form = new MessageFormat(ClerkConstants.INCOME_TITLE_MSG);
            try {
                String[] title = getTitleParam(commssionDate, commssionSrc, principal.getName());
//                String[] title = {};
                data.put("commssionOverview", form.format(title));
            } catch (Exception e) {
                LOGGER.error("查询提成概览接口发生异常，staffId:{}, error:{}", principal.getName(), e);
                String errorCode = ErrorCodeConstants.ERR_0002;
                throw new MobileException(errorCode, ErrorCodeConstants.ERR_MAP.get(errorCode));
            }

            // 来源列表
            try {
                data.put("commssionSrcList", getSources(ClerkConstants.INCOME_SOURCE_KEY));
            } catch (Exception e) {
                LOGGER.error("查询来源列表接口发生异常，staffId:{}, error:{}", principal.getName(), e);
                String errorCode = ErrorCodeConstants.ERR_0002;
                throw new MobileException(errorCode, ErrorCodeConstants.ERR_MAP.get(errorCode));
            }
        }

        // 查询所有有销售提成订单
        try {
            List<StoreManThisMonIncomeDetail> list = biDataDaoService.queryIncomeDetailPage(principal.getName(),
                    commssionDate, commssionSrc, currIndex, pageSize);

            if (null != list && list.size() > 0) {

                List<IncomeOrderRtn> rtnList = Lists.transform(list,
                        new Function<StoreManThisMonIncomeDetail, IncomeOrderRtn>() {
                            @Override
                            public IncomeOrderRtn apply(StoreManThisMonIncomeDetail input) {
                                IncomeOrderRtn rtn = new IncomeOrderRtn();
                                // 小订单
                                rtn.setOrderNo(input.getOmsOrderItemId());
                                // 转换格式yyyy-MM-dd HH:mm:ss
                                rtn.setBookingTime(DateUtils.getDateStrByFormat(input.getOrderTime(),
                                        DateUtils.DEFAULT_TIME_PATTERN));
                                // 转换格式 x 日
                                rtn.setCommssionDate(convertDay(input.getOrderTime()));
                                // 订单金额
                                rtn.setOrderAmount(DJStringUtils.stringFormat(String.valueOf(input.getPayAmount())));
                                // 提成佣金
                                rtn.setCommssionAmount(
                                        DJStringUtils.stringFormat(String.valueOf(input.getPartnumberAmount())));
                                // 来源名称
                                rtn.setCommssionSrcTxt(input.getIncSourceName());
                                // 商品名称
                                rtn.setGoodsName(input.getGoodsName());
                                rtn.setGoodsCode(input.getGoodsCode());
                                return rtn;
                            }
                        });
                data.put("commssionList", rtnList);
            }

        } catch (Exception e) {
            LOGGER.error("查询所有有销售提成订单接口发生异常，staffId:{}, error:{}", principal.getName(), e);
            String errorCode = ErrorCodeConstants.ERR_0002;
            throw new MobileException(errorCode, ErrorCodeConstants.ERR_MAP.get(errorCode));
        }
        MyGsonView view = createGsonView();

        // 取最新统计时间
        try {
            String statisDate = biDataDaoService.getMaxStaticDate(commssionDate);
            data.put("statisDate", statisDate);
        } catch (Exception e) {
            LOGGER.error("查询最新统计时间接口发生异常，staffId:{}, error:{}", principal.getName(), e);
            String errorCode = ErrorCodeConstants.ERR_0002;
            throw new MobileException(errorCode, ErrorCodeConstants.ERR_MAP.get(errorCode));
        }

        view.addStaticAttribute(BaseContants.DATA, data);

        return view;
    }

    /**
     * 
     * 功能描述: 提成明细<br>
     * 〈功能详细描述〉
     *
     * @param omsOrderNo
     * @param dateFormat
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "/queryOrderCommssion.do", method = RequestMethod.POST)
    @ResponseBody
    public ReturnMsg<List<OmsOrderItemPos>> queryOrderCommssion(
            @RequestParam(value = "omsOrderNo", required = true) String omsOrderNo,
            @RequestParam(value = "orderTime", required = true) String dateFormat) {

        LOGGER.debug("queryOrderCommssion IN,omsOrderNo={},orderTime={}", omsOrderNo, dateFormat);
        ReturnMsg<List<OmsOrderItemPos>> result = new ReturnMsg<List<OmsOrderItemPos>>();
        result.setRetFlag(ReturnMsg.FAIL);
        try {
            List<OmsOrderItemPos> data = reportService.queryOmsOrderItemsCommission(omsOrderNo, dateFormat);
            result.setRetFlag(ReturnMsg.SUCCESS);
            result.setData(data);
        } catch (Exception e) {
            LOGGER.error("查询订单的提成信息系统异常！", e);
            result.setErrorMessage("查询订单的提成信息系统异常！");
        }
        return result;

    }

    private Map<String, Object> getDefaultCommssionListData() {
        Map<String, Object> data = new HashMap<String, Object>();

        data.put("commssionOverview", "");
        data.put("commssionSrcList", new ArrayList<SourceRtn>());
        data.put("commssionList", new ArrayList<IncomeOrderRtn>());

        return data;
    }

    /**
     * 日期格式转换 x 日
     * 
     * @param date
     * @return
     */
    private String convertDay(Date date) {
        if (null != date) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar.get(Calendar.DAY_OF_MONTH) + "日";
        }
        return "";
    }

    /**
     * 获取员工提成详情标题参数
     * 
     * @param timeType
     * @param staffId
     * @return
     */
    private String[] getTitleParam(String commssionDate, String commssionSrc, String staffId) {
        // 默认的累计金额,订单数
        String cumulativeInc = "0.00";
        String orderCnt = "0";

        String[] testArgs = new String[3];
        // 转换提成时间
        if (ClerkConstants.LASTMONTH_INCOME.equals(commssionDate)) { // 上月提成
            testArgs[0] = "上月";

            try {
                // 调用查询
                StoreManTotalIncome income = biDataDaoService.queryTotalIncomeBySatffIdAndDate(staffId,
                        DateUtils.getDateStrByFormat(DateUtils.getMaxMonthDate(null), DateUtils.YYYYMMDD_PATTERN),
                        commssionSrc, false);

                if (null != income) {
                    if (null != income.getMonActIncome()) {
                        cumulativeInc = DJStringUtils.stringFormat(income.getMonActIncome().toString());
                    }
                    if (null != income.getMonOrderCnt()) {
                        orderCnt = income.getMonOrderCnt().toString();
                    }
                }
            } catch (Exception e) {
                LOGGER.error("查询上月订单统计接口发生异常，staffId:{}, error:{}", staffId, e);
            }
        } else { // 本月提成
            try {

                // 昨天提成
                if (ClerkConstants.YEASTERDAY_INCOME.equals(commssionDate)) {
                    testArgs[0] = "昨日";
                    // 调用查询
                    StoreManTotalIncome income = biDataDaoService.queryTotalIncomeBySatffIdAndDate(staffId,
                            DateUtils.getNextDayStr(-1, DateUtils.YYYYMMDD_PATTERN), commssionSrc, false);
                    if (null != income) {
                        if (null != income.getActIncome()) {
                            cumulativeInc = DJStringUtils.stringFormat(income.getActIncome().toString());
                        }
                        if (null != income.getOrderCnt()) {
                            orderCnt = income.getOrderCnt().toString();
                        }
                    }

                } else {// 默认本月提成
                    testArgs[0] = "本月";
                    // 调用查询, 如果是一月的首日,不向前取数据
                    StoreManTotalIncome income = biDataDaoService.queryTotalIncomeBySatffIdAndDate(staffId,
                            DateUtils.getNextDayStr(-1, DateUtils.YYYYMMDD_PATTERN), commssionSrc,
                            !DateUtils.isFirstDayByMonth());
                    if (null != income) {
                        if (null != income.getMonActIncome()) {
                            cumulativeInc = DJStringUtils.stringFormat(income.getMonActIncome().toString());
                        }
                        if (null != income.getMonOrderCnt()) {
                            orderCnt = income.getMonOrderCnt().toString();
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.error("查询本月订单统计接口发生异常，staffId:{}, error:{}", staffId, e);
            }
        }
        testArgs[1] = cumulativeInc;
        testArgs[2] = orderCnt;
        return testArgs;
    }

    /**
     * 来源列表拼装 从配置库读配置 拼接组装成对象返回
     * 
     * @return
     */
    private List<SourceRtn> getSources(String key) {
        LOGGER.debug("begin getIncomeSource ");
        List<SourceRtn> list = new ArrayList<SourceRtn>();
        String strs = ConfigUtil.getConfig(ConfigConstants.SAWP_CONFIG_PATH, key, "");

        // 为空或未配置,默认全部来源
        if (null == strs || "".equals(strs)) {
            SourceRtn source = new SourceRtn();
            source.setId("");
            source.setName("全部来源");
            list.add(source);
        } else {
            // 按照分号;区分来源类型,
            String[] sources = strs.split(";");
            SourceRtn source = null;
            for (String sourceStr : sources) {
                if (null != sourceStr && sourceStr.length() > 0) {
                    // 按照减号-区分来源ID,NAME
                    String[] attr = sourceStr.split("-");
                    if (null != attr && attr.length == 2) {
                        source = new SourceRtn();
                        source.setId(attr[0]);
                        source.setName(attr[1]);
                        list.add(source);
                    }
                }
            }
        }
        return list;
    }

    private String changeDateStr(String dateStr) {
        if (null == dateStr || dateStr.length() < 8) {
            dateStr = DateUtils.getNextDayStr(-1, DateUtils.YYYYMMDD_PATTERN);
        }
        return dateStr.substring(0, 4) + "年" + dateStr.substring(4, 6) + "月" + dateStr.substring(6, 8) + "日";
    }
    
    /**
     * 
     * 功能描述: POS渠道发展会员明细查询<br>
     * 〈功能详细描述〉
     *
     * @param promoteDate
     * @param startIndex
     * @param limit
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryPosPromotionList.do")
    public MyGsonView queryPosPromotionList(String promoteDate, 
            Integer startIndex, Integer limit, Principal principal) {
        ReturnMsg<PromotionDetail> retMsg = reportService.queryPosPromotionList(
                promoteDate, startIndex, limit, principal.getName());
        return setGsonView(retMsg);
    }
    
    /**
     * 
     * 功能描述: 实际提成列表（查询上个月）<br>
     * 〈功能详细描述〉
     *
     * @param principal
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryRealCommssionList.do")
    public MyGsonView queryRealCommssionList(Principal principal, int startIndex, int limit) {
        ReturnMsg<StoreManRealIncomeList> retMsg = reportService.queryRealCommssionList(principal.getName(), startIndex, limit);
        return setGsonView(retMsg);
    }
}
